<template>
  <!-- 职位管理 -->
  <div class="app-container">
    <div class="none2-border3 positionlist mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :model="filterForm" :inline="true" @submit.native.prevent>
          <el-form-item label="职位名称:" prop="positionName">
            <el-input
              v-model.trim="filterForm.positionName"
              placeholder="请输入内容"
              style="width: 200px;margin-right:10px"
              class="filter-item limit"
              maxlength="30"
              clearable
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <el-button
          class="filter-item"
          type="primary"
          @click="handleFilter"
        >
          搜索
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['ORG_POSITION_ADD_BUTTON']"
            class="filter-item"
            icon="el-icon-plus"
            type="primary"
            @click="createPositionInfo"
          >
            新增
          </el-button>
          <el-dropdown v-permission="['ORG_POSITION_EXPORT_BUTTON']" style="margin-left: 10px">
            <el-button
              :disabled="positionList.length<=0"
              size="medium"
            >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="handleDownload('all')"
              >导出所有</el-dropdown-item>
              <el-dropdown-item
                @click.native="handleDownload()"
              >导出选中</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="listLoading"
          border
          :data="positionList"
          highlight-current-row
          style="width: 100%;"
          row-key="positionId"
          :header-cell-style="headerCellStyle"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column type="selection" :reserve-selection="true" width="55" />
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            :index="table_index"
          />
          <el-table-column
            v-if="columns[0].show"
            key="positionName"
            prop="positionName"
            label="职位名称"
          />
          <el-table-column
            v-if="columns[1].show"
            key="positionCode"
            prop="positionCode"
            label="职位编码"
          />
          <el-table-column
            v-if="columns[2].show"
            key="positionRemark"
            prop="positionRemark"
            label="备注"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columns[3].show"
            key="statusFlag"
            prop="statusFlag"
            class-name="status-col"
            label="状态"
          >
            <template slot-scope="{ row, $index }">
              <el-switch
                :disabled="!hasAuth"
                :value="row.statusFlag"
                :active-value="1"
                :inactive-value="2"
                @change="statusChange(row.statusFlag, row, $index)"
              />
            </template>
          </el-table-column>
          <el-table-column
            :key="Math.random()"
            :fixed="$store.getters.device == 'mobile'? null :'right' "
            label="操作"
            width="144"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="{ row }">
              <el-button
                v-permission="['ORG_POSITION_UPDATE_BUTTON']"
                size="mini"
                @click="editPositionInfo(row)"
              >
                修改
              </el-button>
              <el-button
                slot="reference"
                v-permission="['ORG_POSITION_DEL_BUTTON']"
                size="mini"
                type="danger"
                @click="removePosition(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="filterForm.pageNo"
          :limit.sync="filterForm.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 职位dialog -->
      <dtDialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :is-loading="loading"
        @closeDialog="resetTemp"
        @comfirmBtn="dialogStatus === 'create' ? createData() : updateData()"
      >
        <el-form
          ref="dataForm"
          slot="content"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="82px"
          style="width: 100%"
        >
          <el-form-item label="职位名称" prop="positionName">
            <el-input v-model.trim="temp.positionName" maxlength="30" show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="职位编码" prop="positionCode">
            <el-input v-model.trim="temp.positionCode" :disabled="dialogStatus === 'update'" maxlength="30" show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="顺序" prop="positionSort">
            <el-input v-model.trim="temp.positionSort" min="0" :oninput="initPositiveInteger(8)" maxlength="8" show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="备注" prop="positionRemark">
            <el-input v-model.trim="temp.positionRemark" show-word-limit maxlength="200" type="textarea" class="limit" />
          </el-form-item>
        </el-form>
      </dtDialog>
    </div>
  </div>
</template>
<script>
import { hasAuth } from '@/framework/utils/hasAuth'
import hrPositionApi from '@/framework/api/hrPosition'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'
import { positiveInteger } from '@/framework/utils/validate'
export default {
  name: 'OrgPosition',
  mixins: [dialogColumn],
  data() {
    return {
      loading: false,
      hasAuth: hasAuth('ORG_POSITION_UPDATE_STATUS'),
      downloadLoading: false,
      listLoading: false,
      positionList: [],
      total: 0,
      filterForm: {
        positionName: '',
        pageNo: 1,
        pageSize: 10
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改职位',
        create: '新增职位'
      },
      temp: {
      },
      // 列信息
      columns: [
        { prop: 'positionName', label: `职位名称`, show: true },
        { prop: 'positionCode', label: `职位编码`, show: true },
        { prop: 'positionRemark', label: `备注`, show: true },
        { prop: 'statusFlag', label: `状态`, show: true }
      ],
      rules: {
        positionName: [{ required: true, message: '请输入职位名称', trigger: 'blur' }, { pattern: /^[^#@%&*¥$*]+$/, message: '不要输入特殊字符' }],
        positionCode: [{ required: true, message: '请输入职位编码', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9]+$/, message: '请输入字母或数字' }
        ],
        positionSort: [{ required: true, message: '请输入职位顺序', trigger: 'blur' }],
        positionRemark: [{ required: false, pattern: /^[^#@%&*¥$*]+$/, message: '不要输入特殊字符' }]
      },
      multipleSelection: [],
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      sysPositionListLength: 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 校验排序规则
    initPositiveInteger(data) {
      return positiveInteger(data)
    },
    // 列表序号
    table_index(index) {
      return (this.filterForm.pageNo - 1) * this.filterForm.pageSize + index + 1
    },
    // 获取页面列表
    getList() {
      this.listLoading = true
      hrPositionApi.fetchPage(this.filterForm).then((res) => {
        this.sysPositionListLength = res.data.rows.length
        this.positionList = res.data.rows
        this.total = res.data.totalRows
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 搜索
    handleFilter() {
      this.$refs.table.clearSelection()
      this.filterForm.pageNo = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      this.handleFilter()
    },
    sortChange(data) {
    },
    // 状态改变
    statusChange(v, row, index) {
      const flag = (v === 1 ? 2 : 1)
      hrPositionApi.updateStatus({
        statusFlag: flag,
        positionId: row.positionId
      }).then((res) => {
        // this.positionList[index].statusFlag = flag
        this.getList()
        this.$dtMessage({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      })
    },

    resetTemp() {
      this.temp = {
      }
    },
    editPositionInfo(row) {
      const that = this
      this.dialogStatus = 'update'
      hrPositionApi.detail(row.positionId).then((res) => {
        that.temp = Object.assign({}, res.data)
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    createPositionInfo() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    // 修改用户请求
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          const tempData = {
            positionCode: this.temp.positionCode,
            positionId: this.temp.positionId,
            positionName: this.temp.positionName,
            positionRemark: this.temp.positionRemark,
            positionSort: this.temp.positionSort
          }
          try {
            hrPositionApi.edit(tempData).then((res) => {
              this.getList()
              this.dialogFormVisible = false
              this.$dtMessage({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    // 创建用户请求
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          const tempData = {
            positionCode: this.temp.positionCode,
            positionName: this.temp.positionName,
            positionRemark: this.temp.positionRemark,
            positionSort: this.temp.positionSort
          }
          try {
            hrPositionApi.add(tempData).then((res) => {
              this.getList()
              this.dialogFormVisible = false
              this.$dtMessage({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    removePosition(row) {
      this.$dtMessageBox({ title: '提示', message: '确定要删除“' + row.positionName + '”吗?', type: 'warning' }).then(() => {
        hrPositionApi.delete(row).then(res => {
          this.getList()
          this.$dtMessage({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.multipleSelection.forEach((item, index, multipleSelection) => {
            if (item.id === row.id) {
              multipleSelection.splice(index, 1)
              return multipleSelection
            } else {
              return multipleSelection
            }
          })
        })
      })
    },
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        con = {
          positionIds: '',
          positionName: ''
        }
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map(res => {
          return res.positionId
        }).join(',')
        con = {
          positionIds: ids,
          positionName: this.filterForm.positionName
        }
      }

      this.downloadLoading = true
      hrPositionApi.exportPostion(con).then(res => {
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const objectUrl = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = objectUrl // 指定下载链接
        a.download = '职位信息' // 指定下载文件名
        a.click()
        URL.revokeObjectURL(a.href) // 释放URL对象
        this.downloadLoading = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
